<template>
  <el-select v-model="id" clearable placeholder="选择学院" @change="handleChange" filterable >
    <el-option
      v-for="item in list"
      :key="item.collegeId"
      :label="item.shortname"
      :value="item.collegeId"
    />
  </el-select>

</template>
<script setup lang="ts">
import { getCollegeList } from '@/api/Dict.ts'
import {ref,watch,defineProps,defineEmits,onMounted} from 'vue'

const list = ref<IDictCollege[]>([]);
const id = ref<string>('');

const props =  defineProps({
  modelValue:{
    type:String,
    required:true
  },
  type:{
    type:String,
    default:''
  }
});

const emits =  defineEmits(['update:modelValue','updateLabel']);

watch(()=>props.modelValue,(newVal)=>{
  id.value = newVal;
});


onMounted(()=>{
  id.value = props.modelValue;
  getCollegeList(props.type).then((res)=>{
    let collegeList = res.data?.list;
    if(collegeList){
      if(collegeList.length > 1){
        collegeList.sort((a,b)=>{
          var id1 = parseInt(a.collegeId);
          var id2 = parseInt(b.collegeId);
          return id1-id2;
        })
      }
      list.value = collegeList;

    }

    if(id.value == null){
        if(list.value.length == 1){
          id.value = list.value[0].collegeId;
          emits('update:modelValue', id.value);
        }
      } 
    }); 
});


function  handleChange(theValue:string) {
      
      emits('update:modelValue', theValue);
      
      var label = '';
      list.value.forEach(ele=>{
        if(ele.collegeId == theValue){
          label = ele.shortname;
        }
      });

      emits('updateLabel', label);
    }

</script>
